# coding: utf-8
import sys
import os
from cgi import escape
from datetime import datetime
from config import CHAT_LOG_FILE, SOCKET_FUNCS_PATH
from config import TORNADO_LOG_FILE, MEMCACHED_HOST, MEMCACHED_PATTERN, MEMCACHED_TTL
import simplejson as json
import subprocess, re
import memcache
import logging

sys.path.append(SOCKET_FUNCS_PATH)
from socketfuncs import send_bot_task

logging.basicConfig(filename = TORNADO_LOG_FILE, level = logging.DEBUG)
# Регулярка для парсинга лога чата
chat_log_regexp = r"^#(\d+) (\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}) (.*)> (.*)$"
mc = memcache.Client([MEMCACHED_HOST], debug=0)

def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)

def secure_string(string):
    #string = string.replace(r'"',r'&quot;').replace("'",r"&quot;")
    return escape(string, True)

def run_shell_command(command):
    return subprocess.Popen([command], shell = True, stdout = subprocess.PIPE) 

def get_last_messages(since_id = None):
    cached = get_last_messages_cached(since_id)
    if cached:
        # logging.info("got from cache: %s"%since_id)
        return cached

    if since_id: lines_count = 5
    else: lines_count = 30
    result = []
    msg_id = '0'
    try:
        s = True
        command = 'tail -n {0} {1}'.format(lines_count, CHAT_LOG_FILE)
        child = run_shell_command(command)
        while s: 
            s = child.stdout.readline()
            matches = re.match(chat_log_regexp, s)
            if matches:
                msg_id = matches.group(1)
                timestamp = datetime.strptime(matches.group(2), "%d.%m.%Y %H:%M:%S")
                one_message = {
                    'id': msg_id,
                    'time': datetime.strftime(timestamp, "%H:%M"), 
                    'nick': secure_string(matches.group(3)),
                    'text': secure_string(matches.group(4)).strip('\r').strip()
                }
                result.append(one_message)
                if msg_id == since_id: result = [] # Мы нашли нужное сообщение since_id. Те, что до него не нужны.
            else:
                # Если сообщение не соответствует формату, 
                # считаем, что это продолжение предыдущего текста
                if result: result[-1]['text'] += "\n" + secure_string(s)

    except Exception as e:
        print >> sys.stderr, "get_last_messages error:", e

    set_last_messages_cache(since_id, [result, msg_id] )
    return result, msg_id

def get_last_messages_cached(since_id = None):
    if not since_id: return None
    return mc.get( str(MEMCACHED_PATTERN%since_id) )

def set_last_messages_cache(since_id, value):
    mc.set( str(MEMCACHED_PATTERN%since_id), value, MEMCACHED_TTL)
    return True

def send_message_to_chat(nick, text):
    try:
        task = {'action': 'chat', 'nickname': nick, 'text': text}
        send_bot_task( json.dumps(task) )
        return True
    except Exception as e:
        print >> sys.stderr, "send_message_to_chat error:", e
